package com.autumn.util;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 
 * @author 杨昌国 2018-08-20 15:16:29
 */
public class Base64Utils {

	/**
	 * 默认编码
	 */
	public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

	/**
	 * 编码
	 * 
	 * @param source
	 *            源
	 * @return
	 */
	public static byte[] encode(byte[] source) {
		if (source == null) {
			return null;
		}
		return Base64.getEncoder().encode(source);
	}

	/**
	 * 编码转为字符串
	 * 
	 * @param source
	 *            源
	 * @param charset
	 *            字符编码类型
	 * @return
	 */
	public static String encodeToString(String source, Charset charset) {
		if (source == null) {
			return null;
		}
		if (charset == null) {
			charset = DEFAULT_CHARSET;
		}
		byte[] result = encode(source.getBytes(charset));
		return new String(result, charset);
	}

	/**
	 * url编码
	 * 
	 * @param source
	 *            源
	 * @return
	 */
	public static byte[] encodeUrlSafe(byte[] source) {
		if (source == null) {
			return null;
		}
		return Base64.getUrlEncoder().encode(source);
	}

	/**
	 * url编码转为字符串
	 * 
	 * @param source
	 *            源
	 * @param charset
	 *            字符编码类型
	 * @return
	 */
	public static String encodeUrlSafeToString(String source, Charset charset) {
		if (source == null) {
			return null;
		}
		if (charset == null) {
			charset = DEFAULT_CHARSET;
		}
		byte[] result = encodeUrlSafe(source.getBytes(charset));
		return new String(result, charset);
	}

	/**
	 * 解码
	 * 
	 * @param source
	 *            源
	 * @return
	 */
	public static byte[] decode(byte[] source) {
		if (source == null) {
			return null;
		}
		return Base64.getDecoder().decode(source);
	}

	/**
	 * 从字符串解码
	 * 
	 * @param source
	 *            源
	 * @param charset
	 *            字符编码类型
	 * @return
	 */
	public static byte[] decodeFromString(String source, Charset charset) {
		if (source == null) {
			return null;
		}
		if (charset == null) {
			charset = DEFAULT_CHARSET;
		}
		if (source.isEmpty()) {
			return new byte[0];
		}
		return decode(source.getBytes(charset));
	}

	/**
	 * url解码
	 * 
	 * @param source
	 *            源
	 * @return
	 */
	public static byte[] decodeUrlSafe(byte[] source) {
		if (source == null) {
			return null;
		}
		return Base64.getUrlDecoder().decode(source);
	}

	/**
	 * 从字符串url解码
	 * 
	 * @param source
	 *            源
	 * @param charset
	 *            字符编码类型
	 * @return
	 */
	public static byte[] decodeUrlSafeFromString(String source, Charset charset) {
		if (source == null) {
			return null;
		}
		if (charset == null) {
			charset = DEFAULT_CHARSET;
		}
		if (source.isEmpty()) {
			return new byte[0];
		}
		return decodeUrlSafe(source.getBytes(charset));
	}

}
